package activities;

import utils.AppPreferences;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import authorization.FacebookAuth;
import authorization.GoogleAuth;
import authorization.IAuthorization;
import authorization.IAuthorization.Site;
import authorization.VkontakteAuth;

import com.mga.wheelcommunity.R;

public class WebActivity extends Activity {
	private IAuthorization _site;
	private WebView webView;
	private final String TAG = "WebActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.web_auth);
		
		setSite(Integer.valueOf(getIntent().getStringExtra("network")));
		
		webView = (WebView) findViewById(R.id.webView);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.clearCache(true);
		
		webView.setWebViewClient(new AuthWebViewClient());
		
		CookieSyncManager.createInstance(this);
		
		String url = _site.getUrl();
		webView.loadUrl(url);
	}
	
	class AuthWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            parseUrl(url);
        }
    }
	
	private void parseUrl(String url) {
		try{
			if(url==null)
				return;
			Log.i(TAG, "url="+url);
			if(url.startsWith(_site.getRedirectUrl())) {
				Intent i = new Intent();
				if(!url.contains("error=")) {
					String[] auth = _site.parseRedirectUrl(url);
					AppPreferences.setAppSharedPref(this, auth[0], auth[1]);
					i.setClass(getApplicationContext(), DrawerActivity.class);
				}
				startActivity(i);
				finish();
			}
		} catch(Exception e) {
			Log.i(TAG, e.toString());
		}
			
	}
	
	private void setSite(int network) {
		Site s = Site.values()[network];
		switch(s) {
		case vkontakte:
			_site = new VkontakteAuth();
			break;
		case facebook:
			_site = new FacebookAuth();
			break;
		case google:
			_site = new GoogleAuth();
			break;
		}
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		Intent i = new Intent();
		i.setClass(this, LoginActivity.class);
		startActivity(i);
	}
}
